var grid;
var form;
var form1;
$(function () {

    $(".select2").select2();

    //给下拉框赋值
    //发送Ajax请求查询编辑中的下拉框的值
    var labId = $("#labId");

    $.post("../tecParamManagement/getAllLabInfo", {
        "_method": "GET"
    }, function (data) {
        labId.html("");
        var options = "<option value=\"0\">--所属实验室--</option>";
        for (var i = 0; i < data.length; i++) {
            options += "<option value=\"" + data[i].id + "\">" + data[i].name + "</option>";
        }
        labId.html(options);
    })

    var pageNo = 1;
    var pageSize = 10;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";
    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        datatype: "json",
        url: '../tecParamManagement/selectAllEquipmentInfo',
        mtype: 'GET',
        page: pageNo,
        postData: {
            "xh": $("#equipmentXH").val(),
            "zzs": $("#equipmentZZS").val(),
            "sbxlh": $("#equipmentXLH").val(),
            "laboratoryId": $("#labId option:selected").val()
        },
        height: 380,
        width: 300,
        colNames: ['设备型号', "设备价格(元)", "设备制造商", "设备序列号", "服务开始时间", "设备备注", "操作"],
        colModel: [
            {name: 'xh', index: 'xh', sortable: false, align: 'center', width: 100},
            {name: 'jg', index: 'jg', sortable: false, align: 'center', width: 80},
            {name: 'zzs', index: 'zzs', sortable: false, align: 'center', width: 100},
            {name: 'sbxlh', index: 'sbxlh', sortable: false, align: 'center', width: 120},
            {name: 'timeStr', index: 'timeStr', sortable: false, align: 'center', width: 120},
            {name: 'bz', index: 'bz', sortable: false, align: 'center', width: 120},
            {
                name: 'isYy', index: 'isYy', fixed: true, sortable: false, resize: false, width: 270,
                formatter: function (cellvalue, options, rowObject) {
                    return "<button class='btn btn-default btn-xs' onclick='showInfo(\"" + rowObject.id + "\")'><i class='fa fa-empire button-in-i'></i>查看图片</button>"
                        + "<button class='btn btn-file btn-xs' onclick='upload(\"" + rowObject.id + "\")'><i class='fa fa-empire button-in-i'></i>上传图片</button>"
                        + "<button class='btn btn-primary btn-xs' onclick='openEdit(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>编辑</button>"
                        + "<button class='btn btn-danger btn-xs' onclick='openDelete(\"" + rowObject.id + "\")'><i class='fa fa-trash button-in-i'></i>删除</button>";
                }
            },
        ],
        viewrecords: true,
        rowNum: pageSize,
        rownumbers: true,//添加左侧行号
        rowList: [10, 15, 20],
        pager: pager_selector,
        altRows: true,
        multiselect: true,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.content .col-xs-12')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
            /*var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);*/
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "正在加载...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });
    //初始化分页条
    showNavGrid(grid_selector, pager_selector);
    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    //添加新设备
    $("#addNewEquipment").click(function () {
        openEdit(0);
    });
    //编辑
    $("#openEdit").click(function () {
        openEdit(str);
    });
    //查询
    $("#queryBtn").click(function () {
        var filters = {
            "xh": $("#equipmentXH").val(),
            "zzs": $("#equipmentZZS").val(),
            "sbxlh": $("#equipmentXLH").val(),
            "laboratoryId": $("#labId option:selected").val()
        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });
    //清空
    $("#clearBtn").click(function () {
        $("#equipmentXH").val("");
        $("#equipmentXLH").val("");
        $("#equipmentZZS").val("");
        // $("#labId option:first").prop("selected", 'selected');
        $("#labId").val(null).trigger("change");
    });
    //保存
    $("#saveBtn").click(function () {
        doSubmit();
    });
    $("#fzrDh").blur(function () {
        //验证格式
        if (isPhoneNo($.trim($("#fzrDh").val())) == false) {
            bootbox.alert("手机号码格式不正确！");
        }
    });

    //导出EXCEL
    $("#exportDataExcel").click(function () {
        var ids = $('#grid-table').jqGrid('getGridParam', 'selarrrow');//获取选择多行的id，那这些id便封装成一个id数组
        if (ids.length == 0) {
            bootbox.alert("请选择有效数据！");
        } else {
            exportDataExcel(ids);
        }
    });
    //下载模板
    $("#template").click(function () {
        exportVehicleInfo();
    });

    //批量新增
    $("#importDataExcel").click(function () {
        importDataExcel();
    });

    //批量删除
    $("#batchDelete").click(function () {
        var ids = $('#grid-table').jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) {
            bootbox.alert("请选择有效数据！");
        } else {
            batchDeleteData(ids);
        }
    });
});

//下载模板到本地
function exportVehicleInfo() {
    bootbox.confirm("您要下载模板吗？", function (result) {
        if (result) {
            location.href = ("../tecParamManagement/exportVehicleInfo");
        }
    });
}

//查看图片
function showInfo(id) {
    clearForm();
    $("#showMyModal").modal();
    $("#modeltitle2").html("设备图片查看");
    //发送ajax请求查询该设备信息
    $.post("../tecParamManagement/selectByPrimaryKey", {
        "id": id,
        "_method": "GET"
    }, function (data) {
        $("#photo").attr("src", "http://localhost/images/" + data[0].photo);
    })
}

//上传
function upload(id) {
    clearForm();
    $("#uploadModal").modal();
    $("#modeltitle3").html("上传设备图片");
    $("#equId").val(id);
}

//上传图片并预览图片
$("input[name='ImgPath']").fileupload({
    url: "../tecParamManagement/upload",
    type: "post",
    secreuri: false,
    fileElementId: "ImgPath",
    dataType: "json",
    autoUpload: true,
    success: function (data) {
        if (data.resultCode == 200) {
            $('#goodsPicture').css('display', 'block');
            $("#goodsPicture").attr("src", "http://localhost/images/" + data.imgPath);
            $("img[name='goodsPicture']").attr("value", "http://localhost/images/" + data.imgPath);
            $("#ImagePath").val(data.imgPath);
        } else {
            bootbox.alert(data.uploadMsg);
        }
    }
});

//上传
$("#uploadBtn").click(function () {
    var id = $("#equId").val();
    var imagePath = $("#ImagePath").val();
    if (imagePath == "") {
        bootbox.alert("请选择图片！");
        return;
    }
    $.post("../tecParamManagement/uploadImage", {
        "id": id,
        "imagePath": imagePath,
        "_method": "PUT"
    }, function (data) {
        if (data.resultCode == 200) {
            bootbox.alert("图片上传成功！")
            $('#uploadModal').modal('hide');
        } else {
            bootbox.alert("图片上传失败！");
        }
    })
});

//导出excel
function exportDataExcel(ids) {
    bootbox.confirm("确定导出数据吗？", function (result) {
        if (result) {
            location.href = ("../tecParamManagement/exportExcel?ids=" + ids);
        }
    });
}

//批量删除
function batchDeleteData(ids) {
    bootbox.confirm("您确定要删除这些记录吗?", function (result) {
        if (result) {
            $.post("../tecParamManagement/batchDeleteData?ids=" + ids, {
                "_method": "DELETE"
            }, function (data) {
                bootbox.alert(data.resultMessage);
                grid.trigger('reloadGrid');
            });
        }
    });
}

// 验证手机号
function isPhoneNo(phone) {
    var pattern = /^1[34578]\d{9}$/;
    return pattern.test(phone);
}

//添加实验室
function addNewBtn() {
    clearForm();
    $("#editmyModal").modal();
    $("#modeltitle1").html("新建实验室信息");
    $("#idLable").css("display", "none");
}

//跳转到回收站
function toTrash() {
    loadPage("../goodsInfo/skipToUserList");
}

//批量新增
function importDataExcel() {
    clearForm();
    $("#importDataExcelModel").modal();
    $("#modeltitle4").html("批量新增设备");
    $("#idLable").css("display", "none");
}

//图片上传
$("input[name='uploadFile']").fileupload({
    url: "../tecParamManagement/UploadExcel",
    type: "post",
    secreuri: false,
    fileElementId: "uploadFile",
    dataType: "json",
    autoUpload: true,
    success: function (data) {
        if (data.resultCode == 200) {
            bootbox.alert(data.uploadMsg);
        } else {
            bootbox.alert(data.uploadMsg);
        }
    }
});

//打开编辑
function openEdit(id) {
    clearForm();
    $("#editmyModal").modal();
    $("#modeltitle1").html("设备技术参数");
    $("#idLable").css("display", "none");
    //发送Ajax请求查询编辑中的下拉框的值
    var labId = $("#laboratoryId");
    $.post("../tecParamManagement/getAllLabInfo", {
        "_method": "GET"
    }, function (data) {
        labId.html("");
        var options = "";
        for (var i = 0; i < data.length; i++) {
            options += "<option value=\"" + data[i].id + "\">" + data[i].name + "</option>";
        }
        labId.html(options);
        //发送ajax请求查询该设备信息
        $.post("../tecParamManagement/selectByPrimaryKey", {
            "id": id,
            "_method": "GET"
        }, function (data) {
            $("#id").val(data[0].id);
            $("#xh").val(data[0].xh);
            $("#jg").val(data[0].jg);
            $("#zzs").val(data[0].zzs);
            $("#sbxlh").val(data[0].sbxlh);
            $("#bz").val(data[0].bz);
            // $("#laboratoryId").find("option[value = '" + data[0].laboratoryId + "']").attr("selected", "true");
            $("#laboratoryId").val(data[0].laboratoryId).trigger("change");
        })
    })
}

//保存编辑后的信息
function doSubmit() {
    $("#loading").removeClass('hide').addClass('show');
    $.post("../tecParamManagement/updateByPrimaryKeySelective?_method=PUT", $('#Eidtform').serialize(), function (data) {
        if (data.resultCode == 201) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
        } else if (data.resultCode == 200) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
            grid.trigger('reloadGrid');
            $('#editmyModal').modal('hide');
        }
    });
}

//删除记录
function openDelete(str) {
    array = str.split(",");
    bootbox.confirm("您确定要将删除此行记录吗?", function (result) {
        if (result) {
            $.post("../tecParamManagement/deleteByPrimaryKey", {
                "id": str,
                "_method": "DELETE",
            }, function (data) {
                bootbox.alert(data.resultMessage);
                grid.trigger('reloadGrid');
            });
        }
    });
}

//清除表单
function clearForm() {
    //清空内容
    $("#id").val("");
    $("#xh").val("");
    $("#sbxh").val("");
    $("#sbxlh").val("");
    $("#jg").val("");
    $("#laboratoryId").val(null).trigger("change");
    $("#zzs").val("");
    $("#bz").val("");
    $('#goodsPicture').css('display', 'none');

    //清除验证状态
    $("#addform .form-group").removeClass('has-info').removeClass('has-error');
}

